# -*- coding: utf-8 -*-
# @Date   : 2020/3/3
# @File   : R26_IC_CreditAccountStatus_Check_2D_XD_OTO.py
# @Author : zhangxuchuo



'''eof
name:征信账户状态校验
code:R26_IC_CreditAccountStatus_Check_2D_XD_OTO
tableName:
columnName:
groups:个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return ""
        elif table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

#信贷交易信息概要  PCO [1..1]   $信贷交易信息概要信息单元  PC02  [0..1]
#被追偿汇总信息段  PC02B [0..1] $被追偿汇总信息  PC02BH  [1..2]/业务类型  PC02BD01  [1..1]


def factor1Pre():
    data = IC_DSJ_2D['data']
    PCO = getTable(data, 'PCO', occurTimes=1)
    if PCO is None:
        return None
    elif PCO == "":
        return 0
    else:
        PC02 = getTable(PCO[0], 'PC02', occurTimes=0)
        if PC02 == [{}] or PC02 == "":
            return 0
        elif PC02 is None:
            return None
        else:
            PC02B = getTable(PC02[0], 'PC02B', occurTimes=0)
            if PC02B == [{}]:
                return 0
            elif PC02B is None or PC02B == "":
                return None
            else:
                PC02BH = getTable(PC02B[0], 'PC02BH', occurTimes=1)
                if PC02BH is None or PC02BH == "":
                    return None
                else:
                    result = []
                    for i in PC02BH:
                        PC02BD01 = i.get('PC02BD01')
                        if PC02BD01 in null_type_list:
                            result.append(None)
                        elif PC02BD01 in ['1', '2']:
                            result.append(1)
                        else:
                            result.append(0)
                    result = filter(lambda x:x is not None, result)
                    if len(result) == 0:
                        return None
                    else:
                        return sum(result)

##借贷账户信息  PDA  [1..1]  借贷账户信息单元  PD01  [0..*]
# 基本信息段  PD01A  [1..1]  $账户类型  PD01AD01  [1..1]
# 最新表现信息段  PD01B  [1..1] $还款状态  PD01BD04  [0..1]
#
def factor2Pre():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        PD01 = getTable(PDA[0], 'PD01', occurTimes=0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            result = []
            for i in PD01:
                try:
                    # 基本信息段
                    PD01A = getTable(i, 'PD01A', 1)
                    # 最新表现信息段
                    PD01B = getTable(i, 'PD01B', 1)

                    if PD01A is None or PD01A == "" or PD01B is None or PD01B == "":
                        result.append(None)
                    else:
                        accountType = PD01A[0].get('PD01AD01')
                        payBackState = PD01B[0].get('PD01BD04') # 可能有
                        if accountType in null_type_list:
                            result.append(None)
                        else:
                            if accountType in ['D1', 'R4', 'R1'] and payBackState in ['B', 'Z', 'G']:
                                result.append(1)
                            else:
                                result.append(0)
                except:
                    result.append(None)
                    continue
            result = filter(lambda x:x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)

#借贷账户信息  PDA  [1..1]  借贷账户信息单元  PD01  [0..*]
# 基本信息段  PD01A  [1..1]  $账户类型  PD01AD01  [1..1]
# 最近 5 年内历史表现信息段  PD01E  [0..1]
# 历史表现信息  PD01EH  [1..60] $还款状态  PD01ED01 [1..1]
def factor3Pre():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        PD01 = getTable(PDA[0], 'PD01', occurTimes=0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            result = []
            for i in PD01:
                # 基本信息段
                PD01A = getTable(i, 'PD01A', 1)
                # 最近 5 年内历史表现信息段
                PD01E = getTable(i, 'PD01E', 0)

                if PD01A is None or PD01A == "" or PD01E is None or  PD01E == "":
                    result.append(None)
                elif PD01E == [{}]:
                    result.append(0)
                else:
                    # 账户类型
                    PD01AD01 = PD01A[0].get('PD01AD01')
                    #
                    # PD01EH = PD01E[0].get('PD01EH')
                    PD01EH = getTable(PD01E[0], 'PD01EH', 1)

                    if PD01EH is None or PD01EH == "":
                        result.append(None)
                        continue

                    if PD01AD01 in ['D1', 'R4', 'R1', 'R2', 'R3']:
                        tmpResult = []
                        for i in PD01EH:
                            state = i.get('PD01ED01')
                            if state not in null_type_list:
                                if state in ['B', 'Z']:
                                    tmpResult.append(1)
                                else:
                                    tmpResult.append(0)
                            else:
                                tmpResult.append(None)
                        tmpResult = filter(lambda x: x is not None, tmpResult)
                        # print tmpResult
                        if len(tmpResult) == 0:
                            result.append(None)
                        else:
                            if sum(tmpResult) == 0:
                                result.append(0)
                            else:
                                result.append(1)
            result = filter(lambda x:x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)


#信贷交易信息概要  PCO [1..1]   $信贷交易信息概要信息单元  PC02  [0..1]
#呆账汇总信息段  PC02C  [0..1] $账户数  PC02CS01  [1..1] 余额  PC02CJ01  [1..1]
def factor4Pre():
    data = IC_DSJ_2D['data']
    PCO = getTable(data, 'PCO', occurTimes=1)
    if PCO is None:
        return None
    elif PCO == "":
        return 0
    else:
        PC02 = getTable(PCO[0], 'PC02', 0)
        if PC02 is None:
            return None
        elif PC02 == [{}] or PC02 == "":
            return 0
        else:
            PC02C = getTable(PC02[0], 'PC02C', 0)
            if PC02C is None or PC02C == "":
                return None
            elif PC02C == [{}]:
                return 0
            else:
                # 余额
                PC02CJ01 = PC02C[0].get('PC02CJ01')
                # $账户数
                PC02CS01 = PC02C[0].get('PC02CS01')
                if isfloat(PC02CJ01) is False and isfloat(PC02CS01) is False:
                    return None
                else:
                    if isfloat(PC02CJ01):
                        if float(PC02CJ01) > 0:
                            return 1
                    if isfloat(PC02CS01):
                        if float(PC02CS01) > 0:
                            return 1
                    return 0

###借贷账户信息  PDA  [1..1]  借贷账户信息单元  PD01  [0..*]
# 基本信息段  PD01A  [1..1]  $账户类型  PD01AD01  [1..1]
# 最新表现信息段  PD01B  [1..1] $账户状态  PD01BD01  [1..1]
def factor5678Pre():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            result = []
            for i in PD01:
                try:
                    # 基本信息段
                    PD01A = getTable(i, 'PD01A', 1)
                    # 最新表现信息段
                    PD01B = getTable(i, 'PD01B', 1)
                    #最近一次月度表现信息段
                    PD01C = getTable(i, 'PD01C', 0)

                    if PD01A is None or PD01A == "" or PD01B is None or PD01B == "":
                        result.append(None)
                        continue
                    else:
                        # 账户类型 必须有
                        accountType = PD01A[0].get('PD01AD01')
                        # 账户状态 必须有
                        accountState = PD01B[0].get('PD01BD01')
                        if accountState in null_type_list:
                            try:
                                accountState = PD01C[0].get('PD01CD01')
                            except:
                                accountState = PD01B[0].get('PD01BD01')
                        if accountType in null_type_list or accountState in null_type_list:
                            result.append(None)
                            continue
                        else:
                            if accountType == 'D1':
                                if accountState in ['4', '6', '7', '8']:
                                    result.append(1)
                                else:
                                    result.append(0)
                            elif accountType == 'R1':
                                if accountState in ['4', '5', '6', '8']:
                                    result.append(1)
                                else:
                                    result.append(0)
                            elif accountType == 'R4':
                                if accountState in ['4', '6', '8']:
                                    result.append(1)
                                else:
                                    result.append(0)
                            elif accountType == 'R2' or accountType == 'R3':
                                if accountState in ['2', '5', '31', '8']:
                                    result.append(1)
                                else:
                                    result.append(0)
                            else:
                                result.append(0)
                except:
                    result.append(None)
                    continue

            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)



###借贷账户信息  PDA  [1..1] 借贷账户信息单元  PD01  [0..*]
#特殊交易信息段  PD01F  [0..1]
#特殊交易信息  PD01FH  [1..999]   特殊交易个数  PD01FS01  [1..1]  无
#特殊交易类型  PD01FD01  [1..1]
def factor9Pre():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            result = []
            for i in PD01:
                PD01F = getTable(i, 'PD01F', 0)
                if PD01F == [{}]:
                    result.append(0)
                elif PD01F is None or PD01F == "":
                    result.append(None)
                else:
                    PD01FH = PD01F[0].get('PD01FH')
                    if PD01FH in null_type_list:
                        result.append(None)
                        continue
                    else:
                        for j in PD01FH:
                            PD01FD01 = j.get('PD01FD01')
                            if PD01FD01 in null_type_list:
                                result.append(None)
                            elif PD01FD01 in ['3', '6', '8', '12', '13', '11', '17', '14']:
                                result.append(1)
                            else:
                                result.append(0)
            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)


###借贷账户信息  PDA  [1..1]  借贷账户信息单元  PD01  [0..*]
# 基本信息段  PD01A  [1..1]  业务种类  PD01AD03  [0..1]
def factor14Pre():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            result = []
            for i in PD01:
                try:
                    # 基本信息段
                    PD01A = getTable(i, 'PD01A', 1)
                    if PD01A is None or PD01A == "":
                        result.append(None)
                        continue
                    else:
                        # 业务种类
                        businessType = PD01A[0].get('PD01AD03')
                        if businessType in null_type_list:
                            result.append(None)
                            continue
                        if businessType in ['A1','B1']:
                            result.append(1)
                        else:
                            result.append(0)
                except:
                    result.append(None)
                    continue
            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)

###借贷账户信息  PDA  [1..1]  借贷账户信息单元  PD01  [0..*]
# 基本信息段  PD01A  [1..1]  #账户类型  PD01AD01  [1..1]
###
# 最近一次月度表现信息段  PD01C  [0..1]
# 账户状态  PD01CD01  [1..1]

def factor10_13Pre():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            result = []
            for i in PD01:
                try:
                    # 基本信息段
                    PD01A = getTable(i, 'PD01A', 1)
                    PD01C = getTable(i, 'PD01C', 0)
                    if PD01A is None or PD01A == "" or PD01C is None or PD01C == "":
                        result.append(None)
                    elif PD01C == [{}]:
                        result.append(0)
                    else:
                        # 账户类型 必须有
                        accountType = PD01A[0].get('PD01AD01')
                        accountState = PD01C[0].get('PD01CD01')
                        if accountType in null_type_list or accountState in null_type_list:
                            result.append(None)
                            continue
                        if accountType == 'D1':
                            if accountState in ['4', '6', '7', '8']:
                                result.append(1)
                            else:
                                result.append(0)
                        elif accountType == 'R1':
                            if accountState in ['4', '5', '6', '8']:
                                result.append(1)
                            else:
                                result.append(0)
                        elif accountType == 'R4':
                            if accountState in ['4', '6', '8']:
                                result.append(1)
                            else:
                                result.append(0)
                        elif accountType == 'R2' or accountType == 'R3':
                            if accountState in ['2', '5', '31', '8']:
                                result.append(1)
                            else:
                                result.append(0)
                        else:
                            result.append(0)
                except:
                    result.append(None)
            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)


def factor15():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            result = []
            for i in PD01:
                try:
                    # 基本信息段
                    PD01A = getTable(i, 'PD01A', 1)
                    # 最新表现信息段
                    PD01B = getTable(i, 'PD01B', 1)

                    if PD01A is None or PD01A == "" or PD01B is None or PD01B == "":
                        result.append(None)
                        continue
                    else:
                        # 账户类型 必须有
                        accountType = PD01A[0].get('PD01AD01')
                        # 账户状态 必须有
                        accountState = PD01B[0].get('PD01BD04')

                        if accountType in null_type_list or accountState in null_type_list:
                            result.append(None)
                            continue
                        else:
                            if accountType in ['D1', 'R4', 'R1']:
                                if accountState == 'D':
                                    result.append(1)
                                else:
                                    result.append(0)
                            else:
                                result.append(0)
                except:
                    result.append(None)
                    continue

            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)


def factor16():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        PD01 = getTable(PDA[0], 'PD01', occurTimes=0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            result = []
            for i in PD01:
                # 基本信息段
                PD01A = getTable(i, 'PD01A', 1)
                # 最近 5 年内历史表现信息段
                PD01E = getTable(i, 'PD01E', 0)

                if PD01A is None or PD01A == "" or PD01E is None or PD01E == "":
                    result.append(None)
                elif PD01E == [{}]:
                    result.append(0)
                else:
                    # 账户类型
                    PD01AD01 = PD01A[0].get('PD01AD01')
                    #
                    # PD01EH = PD01E[0].get('PD01EH')
                    PD01EH = getTable(PD01E[0], 'PD01EH', 1)

                    if PD01EH is None or PD01EH == "":
                        result.append(None)
                        continue

                    if PD01AD01 in ['D1', 'R4', 'R1', 'R2', 'R3']:
                        tmpResult = []
                        for i in PD01EH:
                            state = i.get('PD01ED01')
                            if state not in null_type_list:
                                if state in ['D']:
                                    tmpResult.append(1)
                                else:
                                    tmpResult.append(0)
                            else:
                                tmpResult.append(None)
                        tmpResult = filter(lambda x: x is not None, tmpResult)
                        # print tmpResult
                        if len(tmpResult) == 0:
                            result.append(None)
                        else:
                            if sum(tmpResult) == 0:
                                result.append(0)
                            else:
                                result.append(1)
            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)





def factor19():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        PD01 = getTable(PDA[0], 'PD01', occurTimes=0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            result = []
            for i in PD01:
                # 基本信息段
                PD01A = getTable(i, 'PD01A', 1)
                # 最近 5 年内历史表现信息段
                PD01E = getTable(i, 'PD01E', 0)

                if PD01A is None or PD01A == "" or PD01E is None or PD01E == "":
                    result.append(None)
                elif PD01E == [{}]:
                    result.append(0)
                else:
                    # 账户类型
                    PD01AD01 = PD01A[0].get('PD01AD01')
                    # 业务种类（PD01AD03）
                    PD01AD03 = PD01A[0].get('PD01AD03')

                    # PD01EH = PD01E[0].get('PD01EH')
                    PD01EH = getTable(PD01E[0], 'PD01EH', 1)

                    if PD01EH is None or PD01EH == "":
                        result.append(None)
                        continue

                    if PD01AD01 in ['D1', 'R4', 'R1', 'R2', 'R3']:
                        tmpResult = []
                        for i in PD01EH:
                            state = i.get('PD01ED01')
                            month = i.get('PD01ER03')

                            if state not in null_type_list:
                                if state == 'G':
                                    if PD01AD03 == '13' and month in ['2018-06', '2018-07', '2018-08']:
                                        tmpResult.append(0)
                                    else:
                                        tmpResult.append(1)
                                else:
                                    tmpResult.append(0)
                            else:
                                tmpResult.append(None)
                        tmpResult = filter(lambda x: x is not None, tmpResult)
                        # print tmpResult
                        if len(tmpResult) == 0:
                            result.append(None)
                        else:
                            if sum(tmpResult) == 0:
                                result.append(0)
                            else:
                                result.append(1)
            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)

###借贷账户信息  PDA  [1..1] 借贷账户信息单元  PD01  [0..*]
#特殊交易信息段  PD01F  [0..1]
#特殊交易信息  PD01FH  [1..999]   特殊交易个数  PD01FS01  [1..1]  无
#特殊交易类型  PD01FD01  [1..1]
def factor20Pre():
    data = IC_DSJ_2D['data']
    PDA = getTable(data, 'PDA', occurTimes=1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            result = []
            for i in PD01:
                PD01F = getTable(i, 'PD01F', 0)
                if PD01F == [{}]:
                    result.append(0)
                elif PD01F is None or PD01F == "":
                    result.append(None)
                else:
                    PD01FH = PD01F[0].get('PD01FH')
                    if PD01FH in null_type_list:
                        result.append(None)
                        continue
                    else:
                        for j in PD01FH:
                            PD01FD01 = j.get('PD01FD01')
                            PD01FR01 = j.get('PD01FR01')
                            try:
                                yearmonth = int(Formate(PD01FR01))
                            except:
                                yearmonth = 0
                            if PD01FD01 in null_type_list:
                                result.append(None)
                            elif PD01FD01 in ['1','16'] and (yearmonth < 20200125 or yearmonth > 20211231):
                                result.append(1)
                            else:
                                result.append(0)
            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)

def Check_A():
    Factor1 = factor1Pre()
    Factor2 = factor2Pre()
    Factor3 = factor3Pre()
    Factor4 = factor4Pre()
    Factor5 = factor5678Pre()
    Factor6 = factor9Pre()
    Factor7 = factor10_13Pre()
    Factor8 = factor14Pre()
    Factor9 = factor19()
    Factor10 = factor20Pre()
    if Factor1 is None and Factor2 is None and Factor3 is None and Factor4 is None \
        and Factor5 is None and Factor6 is None and Factor7 is None and Factor8 is None and Factor9 is None and Factor10 is None:
        return None
    else:
        if Factor1 is None:
            Factor1 = 0
        if Factor2 is None:
            Factor2 = 0
        if Factor3 is None:
            Factor3 = 0
        if Factor4 is None:
            Factor4 = 0
        if Factor5 is None:
            Factor5 = 0
        if Factor6 is None:
            Factor6 = 0
        if Factor7 is None:
            Factor7 = 0
        if Factor8 is None:
            Factor8 = 0
        if Factor9 is None:
            Factor9 = 0
        if Factor10 is None:
            Factor10 = 0
        Factor = Factor1 + Factor2 + Factor3 + Factor4 + Factor5 + Factor6 + Factor7 + Factor8 + Factor9  + Factor10
        return Factor


def Check_B():
    Factor15 = factor15()
    Factor16 =  factor16()


    if Factor15 is None and Factor16 is None  :
        return None
    else:
        if Factor15 is None:
            Factor15 = 0
        if Factor16 is None:
            Factor16 = 0

        Factor = Factor15 + Factor16
        return Factor

def CreditAccountStatus_Check():
    checkA = Check_A()
    checkB = Check_B()
    if checkA is None and checkB is None:
        return u'缺失值'
    else:
        if checkA is None:
            checkA = 0
        if checkB is None:
            checkB = 0
        if checkA  > 0:
            factor = 2
        else:
            if checkB > 1:
                factor = 2
            elif checkB == 1:
                factor = 1
            else:
                factor = 0
        return factor



result = CreditAccountStatus_Check()
